package com.zenithsun.common.bean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.annotation.JSONField;

/**
 * TreeItem是存储树形结构的bean，用于展示树形结构的列表
 * 
 * @author wanglei@enersun.com.cn
 */
public class TreeItem implements Comparable<TreeItem> {

	public TreeItem() {

	}

	public TreeItem(String id, String text, String parentId) {
		this.id = id;
		this.text = text;
		this.parentId = parentId;
	}

	public TreeItem(String id,String code, String text, String parentId) {
		this.id = id;
		this.code=code;
		this.text = text;
		this.parentId = parentId;
	}
	
	/**
	 * 当前节点的ID
	 */
	private String id;

	/**
	 * 当前数据的CODE
	 */
	private String code;
	
	/**
	 * 节点显示的名称
	 */
	private String text;

	/**
	 * 是否顶级节点
	 */
	private boolean top;

	/**
	 * 排序序号，该属性不参与序列化
	 */
	@JSONField(serialize = false)
	private int orderNo;

	/**
	 * 父节点，该属性不参与序列化
	 */
	@JSONField(serialize = false)
	private String parentId;

	/**
	 * 子节点列表
	 */
	private List<TreeItem> nodes;

	public int getOrderNo() {
		return orderNo;
	}

	public void setOrderNo(int orderNo) {
		this.orderNo = orderNo;
	}
	
	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public List<TreeItem> getNodes() {
		return nodes;
	}

	public void setNodes(List<TreeItem> nodes) {
		this.nodes = nodes;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}
	
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}
	
	public boolean isTop() {
		return top;
	}

	public void setTop(boolean top) {
		this.top = top;
	}
	/**
	 * 实现对TreeItem的排序<br/>
	 * 返回1为升序，-1位降序
	 */
	@Override
	public int compareTo(TreeItem o) {
		if (o != null) {
			if (this.getOrderNo() > o.getOrderNo()) {
				return 1;
			} else if (this.getOrderNo() == o.getOrderNo()) {
				return 0;
			}
		}
		return -1;
	}

	/**
	 * 创建TreeItem的List，并构建父子关系后进行排序
	 * @param ncmap
	 * @return List<TreeItem>
	 */
	public static List<TreeItem> buildTreeItemList(Map<String, TreeItem> ncmap) {
		// 建立TreeItem的父子关系
		List<TreeItem> listItem = new ArrayList<TreeItem>();
		Iterator<Entry<String, TreeItem>> iterTree = ncmap.entrySet().iterator();
		while (iterTree.hasNext()) {
			TreeItem tempTreeItem = iterTree.next().getValue();
			TreeItem pTempTreeItem = ncmap.get(tempTreeItem.getParentId());
			if (pTempTreeItem != null) {
				// 不要在TreeItem中初始化Nodes，否则在前台展示的时候会把空值带出来。
				if (pTempTreeItem.getNodes() == null) {
					pTempTreeItem.setNodes(new ArrayList<TreeItem>());
				}
				pTempTreeItem.getNodes().add(tempTreeItem);
			} else {
				tempTreeItem.setTop(true);
				listItem.add(tempTreeItem);
			}
		}
		Collections.sort(listItem);
		return listItem;
	}
}